package com.oriole.admin.config.uaa;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso;
import org.springframework.boot.autoconfigure.security.oauth2.resource.AuthoritiesExtractor;
import org.springframework.boot.autoconfigure.security.oauth2.resource.PrincipalExtractor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 * Created by IntelliJ IDEA.
 *
 * @author doublelife
 * Date: 2020/8/2 22:57
 * description:
 */
@EnableOAuth2Sso
@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
@EnableWebSecurity
@ConditionalOnExpression("'${oriole.login-type}'.equals('uaa')")
public class UaaWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {

    @Value("${auth-server}")
    private String authServer;

    @Bean
    public PrincipalExtractor principalExtractor() {
        return new OriolePrincipalExtractor();
    }

    @Bean
    public AuthoritiesExtractor authoritiesExtractor() {
        return new OrioleAuthoritiesExtractor();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .headers().frameOptions().disable()
                // 权限不足跳转 /401
                .and().exceptionHandling().accessDeniedPage("/401")
                .and().antMatcher("/**").authorizeRequests()
                // swagger2 开始
                .antMatchers("/doc.html/**").permitAll()
                .antMatchers("/doc.html#/**").permitAll()
                .antMatchers("/webjars/**").permitAll()
                .antMatchers("/swagger-ui.html/**").permitAll()
                .antMatchers("/swagger-resources/**").permitAll()
                .antMatchers("/v2/api-docs/**").permitAll()
                // swagger2 结束
                .anyRequest().authenticated()
                .and().logout().logoutSuccessUrl(authServer + "/exit");
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/common/**");
        super.configure(web);
    }
}
